package cn.com.gome.sn.outapi.utils;

import cn.com.gome.frame.logger.HLogger;
import cn.com.gome.frame.logger.LoggerManager;

import javax.servlet.http.HttpServletRequest;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class HttpUtil {

	private static HLogger logger = LoggerManager.getLoger("HttpUtil");

	/**
	 * 获取HttpServletRequest对象中Attribute
	 * @param request
	 * @return
	 */
	public static final Map<String, Object> getRequestAttributeMap(HttpServletRequest request){

		Enumeration<?> rnames = request.getParameterNames();

		Map<String, Object> map = new HashMap<String, Object>();
		for (Enumeration<?> e = rnames; e.hasMoreElements();) {
			String thisName = e.nextElement().toString();
			Object thisValue = request.getAttribute(thisName);
			map.put(thisName, thisValue);
		}

		return map;

	}

	/**
	 * 获取HttpServletRequest对象中Parameter
	 * @param request
	 * @return
	 */
	public static final Map<String, Object> getRequestParameterMap(HttpServletRequest request){

		Enumeration<?> rnames = request.getParameterNames();

		Map<String, Object> map = new HashMap<String, Object>();
		for (Enumeration<?> e = rnames; e.hasMoreElements();) {
			String thisName = e.nextElement().toString();
			Object thisValue = request.getParameter(thisName);
			map.put(thisName, thisValue);
		}

		return map;

	}

	/**
	 * 获取客户端IP
	 * @param request
	 * @return
	 */
	public static final String getIpAddr(HttpServletRequest request) {

		String ip = request.getHeader("X-Forwarded-For");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}

		return ip;

	}

	public static final Map<String,String> DEFAULT_JSON_HEADER_UTF_8= new HashMap<String, String>();

	static{
		DEFAULT_JSON_HEADER_UTF_8.put("Content-Type", "application/json;charset=utf-8");
	}


	public static StringBuffer submitPost(String url, String paramContent) {
		StringBuffer responseMessage = null;
		java.net.URLConnection connection = null;
		java.net.URL reqUrl = null;
		OutputStreamWriter reqOut = null;
		InputStream in = null;
		BufferedReader br = null;
		String param = paramContent;
		try {
			responseMessage = new StringBuffer();
			reqUrl = new java.net.URL(url);
			connection = reqUrl.openConnection();
			connection.setDoOutput(true);
			reqOut = new OutputStreamWriter(connection.getOutputStream());
			reqOut.write(param);
			reqOut.flush();
			int charCount = -1;
			in = connection.getInputStream();
			br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
			while ((charCount = br.read()) != -1) {
				responseMessage.append((char) charCount);
			}
		} catch (Exception ex) {
			logger.error("url=" + url + "?" + paramContent + "\n", ex);
		} finally {
			try {
				if(in!=null){
					in.close();
				}
				if(reqOut!=null){
					reqOut.close();
				}
			} catch (Exception e) {
				logger.error("paramContent=" + paramContent + "|err=", e);
			}

		}
		return responseMessage;
	}

	public static String submitGet(String strUrl) {
		URLConnection connection = null;
		BufferedReader reader = null;
		String str = null;
		try {
			URL url = new URL(strUrl);
			connection = url.openConnection();
			connection.setDoInput(true);
			connection.setDoOutput(false);
			reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String lines;
			StringBuffer linebuff = new StringBuffer("");
			while ((lines = reader.readLine()) != null) {
				linebuff.append(lines);
			}
			str = linebuff.toString();
		} catch (Exception e) {
			logger.error("submitGet发生异常", e);
		} finally {
			try {
				if(reader!=null){
					reader.close();
				}
			} catch (Exception e) {
				logger.error("submitGet发生异常", e);
			}
		}
		return str;
	}

	/**
	 * 提交的时候设置header,主要的header包括<br>
	 * Content-Type: text/json;charset=utf-8<br>
	 * Accept: text/json
	 * @param url
	 * @param paramContent
	 * @param headers
	 * @return
	 */
	public static StringBuffer submitPostByHeader(String url,String paramContent, Map<String, String> headers) {
		StringBuffer responseMessage = null;
		java.net.URLConnection connection = null;
		java.net.URL reqUrl = null;
		OutputStreamWriter reqOut = null;
		InputStream in = null;
		BufferedReader br = null;
		String param = paramContent;
		try {
			responseMessage = new StringBuffer();
			reqUrl = new java.net.URL(url);
			connection = reqUrl.openConnection();
			connection.setDoOutput(true);
			connection.setConnectTimeout(3000);//设置连接主机超时（单位：毫秒）
			connection.setReadTimeout(3000);//设置从主机读取数据超时（单位：毫秒）
			for(Map.Entry<String, String> e :headers.entrySet()){
				connection.setRequestProperty(e.getKey(), e.getValue());
			}
			reqOut = new OutputStreamWriter(connection.getOutputStream());
			reqOut.write(param);
			reqOut.flush();
			in = connection.getInputStream();
			ByteArrayOutputStream bao = new ByteArrayOutputStream();
			byte[] tmp = new byte[512];
			int count=0;
			while((count=in.read(tmp))>0){
				bao.write(tmp,0,count);
			}
			String msg = new String(bao.toByteArray(),"UTF-8");
			responseMessage.append(msg);
		} catch (Exception ex) {
			logger.error("url=" + url + "?" + paramContent + "\n", ex);
		} finally {
			try {
				if(in!=null){
					in.close();
				}
				if(reqOut!=null){
					reqOut.close();
				}
			} catch (Exception e) {
				logger.error("paramContent=" + paramContent + "|err=", e);
			}

		}
		return responseMessage;
	}
	/**
	 * 提交的时候设置header,主要的header包括<br>
	 * Content-Type: text/json;charset=utf-8<br>
	 * Accept: text/json
	 * @param strUrl
	 * @param headers
	 * @return
	 */
	public static String submitGetByHeader(String strUrl, Map<String, String> headers) {
		URLConnection connection = null;
		BufferedReader reader = null;
		String str = null;
		try {
			URL url = new URL(strUrl);
			connection = url.openConnection();
			connection.setDoInput(true);
			connection.setDoOutput(false);
			for(Map.Entry<String, String> e :headers.entrySet()){
				connection.setRequestProperty(e.getKey(), e.getValue());
			}
			reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String lines;
			StringBuffer linebuff = new StringBuffer("");
			while ((lines = reader.readLine()) != null) {
				linebuff.append(lines);
			}
			str = linebuff.toString();
		} catch (Exception e) {
			logger.error("submitGetByHeader发生异常", e);
		} finally {
			try {
				if(reader!=null)reader.close();
			} catch (Exception e) {
				logger.error("submitGetByHeader发生异常", e);
			}
		}
		return str;
	}
}